<script setup lang="ts">
import type { ActionSheetAction } from 'vant';
import { onMounted } from 'vue';
import { ref } from 'vue';
import { request } from '@/api/index'
import { closeToast, showLoadingToast, showToast } from 'vant';
import base64ToBlob from 'b64-to-blob'

// 0. 获取数据回显
const profileInfo = ref<ProfileInfo>({} as ProfileInfo)
const getProfileInfo = async () => {
  // 加载提示
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0 // 不关闭加载提示
  })
  // 请求数据
  const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
  // 关闭提示  
  closeToast()
  console.log(res.data.result)
  profileInfo.value = res.data.result
  // 把日期设置给初始变量
  birthday.value = res.data.result.birthday.split('-')
}
getProfileInfo()


// 1. 头像处理
const showAvatar = ref(false)
const actions = [
  { name: '相册' },
  { name: '拍照' }
]
const onSelect = async (action: ActionSheetAction, index: number) => {
  if (index === 0) {
    const res = await mk.pickerPhoto()
    onUploadAvatar(res)
  } else if (index === 1) {
    const res = await mk.pickerCamera()
    onUploadAvatar(res)
  }
}

const onUploadAvatar = async (str: string) => {
  try {
    // 1. 隐藏弹层
    showAvatar.value = false
    // 2. 把base64编码转成blob格式的图片文件对象
    const image = base64ToBlob(str, 'image/jpeg')
    // 3. 调用上传图片的接口
    // 加载提示
    showLoadingToast({
      message: '上传中...',
      forbidClick: true,
      duration: 0 // 不关闭加载提示
    })
    // 创建formData对象
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpg')
    // 调用上传接口
    const res = await request.post<MkResponse<{ avatar: string }>>('member/profile/avatar', fd)
    profileInfo.value.avatar = res.data.result.avatar
    // 关闭提示
    closeToast()

    // 4. 上传成功去修改原生侧的头像
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
    showToast({ message: '上传成功' })
  } catch (error) {
    showToast('上传头像失败')
  }
}

// 2. 日期处理
// 2.1 控制弹层的显示和隐藏
const showBirthdayPopup = ref(false)
// 2.2 双向绑定的日期
// 默认是把当前日期作为初始值
const birthday = ref([
  new Date().getFullYear().toString(),
  String(new Date().getMonth() + 1),
  new Date().getDate().toString()
])
// 2.3 选择的日期
const selectBirthday = (obj: { selectedValues: string[] }) => {
  showBirthdayPopup.value = false
  // ['1982', '1', '12'] -> 1982-1-12
  profileInfo.value.birthday = obj.selectedValues.join('-')
}

// 3. 所在地处理
const showLocationPopup = ref(false)
const areaColumns = ref<AreaColumns>()
onMounted(async () => {
  const res = await mk.getAreaColumns()
  console.log(res)
  areaColumns.value = res
})
const selectLocation = (obj: { selectedValues: string[] }) => {
  showLocationPopup.value = false
  // 3.1 省市区的编码
  profileInfo.value.provinceCode = Number(obj.selectedValues[0])
  profileInfo.value.cityCode = Number(obj.selectedValues[1])
  profileInfo.value.countyCode = Number(obj.selectedValues[2])
  // 3.2 拼接完整的地址
  const province = areaColumns.value?.province_list[Number(obj.selectedValues[0])]
  const city = areaColumns.value?.city_list[Number(obj.selectedValues[1])]
  const county = areaColumns.value?.county_list[Number(obj.selectedValues[2])]
  profileInfo.value.fullLocation = `${province} ${city} ${county}`
}

// 4. 选择职业
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
const showProfessionPopup = ref(false)
const onConfirm = (obj: { selectedValues: string[] }) => {
  showProfessionPopup.value = false
  // console.log(obj.selectedValues);
  profileInfo.value.profession = obj.selectedValues[0]
}

// 5. 提交
const btnLoading = ref(false)
const onSaveProfile = async () => {
  btnLoading.value = true
  mk.vibrator()
  // 加载提示
  showLoadingToast({
    message: '正在提交...',
    forbidClick: true,
    duration: 0 // 不关闭加载提示
  })
  await request.put('member/profile', profileInfo.value)
  closeToast()

  btnLoading.value = false

  // 修改应用侧的昵称
  const user = mk.queryUser()
  user.nickname = profileInfo.value.nickname
  mk.updateUser(user)

  showToast('更新成功')
}

</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像 -->
    <div class="avatar">
      <van-image round class="avatar-img" width="100" height="100" :src="profileInfo.avatar"
        @click="showAvatar = true" />
      <div class="avatar-btn" @click="showAvatar = true">
        修改头像
      </div>
    </div>
    <van-action-sheet style="padding-bottom: 20px;" v-model:show="showAvatar" :actions="actions" @select="onSelect"
      cancel-text="取消" />
    <!-- 用户信息 -->
    <van-cell-group>
      <van-field v-model="profileInfo.account" label="账号" readonly />
      <van-field v-model="profileInfo.nickname" label="昵称" placeholder="请输入昵称" />
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profileInfo.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field v-model="profileInfo.birthday" label="生日" placeholder="请选择日期" readonly
        @click="showBirthdayPopup = true" />
      <van-popup position="bottom" v-model:show="showBirthdayPopup">
        <van-date-picker v-model="birthday" title="选择日期" :min-date="new Date(1980, 0, 1)" :max-date="new Date()"
          @cancel="showBirthdayPopup = false" @confirm="selectBirthday" />
      </van-popup>
      <van-field v-model="profileInfo.fullLocation" label="所在地" placeholder="请选择所在地" readonly
        @click="showLocationPopup = true" />
      <van-popup v-model:show="showLocationPopup" position="bottom">
        <van-area title="请选择所在地" :area-list="areaColumns" @cancel="showLocationPopup = false"
          @confirm="selectLocation" />
      </van-popup>
      <van-field v-model="profileInfo.profession" label="职业" placeholder="请选择职业" readonly
        @click="showProfessionPopup = true" />
      <van-popup v-model:show="showProfessionPopup" position="bottom">
        <van-picker title="选择职业" :columns="columns" @confirm="onConfirm" @cancel="showProfessionPopup = false" />
      </van-popup>
    </van-cell-group>
    <div class="submit">
      <van-button :loading="btnLoading" ound block type="primary" @click="onSaveProfile">保存资料</van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>